import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:du_application/model/UploadModel.dart';
import 'package:du_application/provide/AffairProvider.dart';
import 'package:du_application/routes/application.dart';
import 'package:du_application/units/image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provide/provide.dart';

class ImagePickerWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ImagePickerState();
  }
}

class _ImagePickerState extends State<ImagePickerWidget> {
  var _imgPath;
  var ispic = false;
  TouchMovePainter painter;
  //静止状态下的offset
  Offset idleOffset = Offset(0, 0);
  //本次移动的offset
  Offset moveOffset = Offset(0, 0);
  //最后一次down事件的offset
  Offset lastStartOffset = Offset(0, 0);
  Offset image = Offset(0, 0);
  GlobalKey anchorKey = GlobalKey();
 
  @override
  void initState() {
    painter = TouchMovePainter();
    
    _openGallery();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Provide<AffairProvider>(builder: (context, child, index) {
     return FlutterEasyLoading(
        child: Scaffold(
          appBar: PreferredSize(
              child: AppBar(
                leading: FlatButton(
                  onPressed: () {
                      index.record();
                       Navigator.of(context).popUntil(ModalRoute.withName('/person'));
                  },
                  child: Icon(
                    Icons.arrow_back,
                    color: Colors.white,
                  ),
                ),
                actions: [
                  FlatButton(
                    onPressed: () {
                      Application.router.navigateTo(context, "/affairs");
                    },
                    child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: ScreenUtil().setWidth(40),
                            vertical: ScreenUtil().setWidth(10)),
                        color: Colors.cyan[400],
                        child:
                            Text("下一步", style: TextStyle(color: Colors.white))),
                  )
                ],
                backgroundColor: Color.fromRGBO(0, 0, 0, 1),
              ),
              preferredSize:
                  Size.fromHeight(MediaQuery.of(context).size.height * 0.07)),
          body: Stack(alignment: Alignment.bottomCenter, children: [
            Stack(children: [
              Container(
                  color: Colors.black,
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height -
                      MediaQuery.of(context).size.height * 0.07,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        constraints: BoxConstraints(

          
       maxHeight:  MediaQuery.of(context).size.height -MediaQuery.of(context).size.height * 0.30,
 maxWidth:MediaQuery.of(context).size.width
  ),
                child: index.url==null?Container():CachedNetworkImage(
                   key: anchorKey,
                                                imageUrl:
                                                    index.url,
                                                fit: BoxFit.cover,
                                                placeholder: (context, url) =>
                                                    Image.asset(
                                                        'assets/loading.jpg'),
                                              )),
                    ],
                  )),
              index.tips != null
                  ? Transform.translate(
                      offset: moveOffset,
                      child: Container(
                        width: ScreenUtil().setWidth(400),
                        child: GestureDetector(
                            onPanStart: (detail) {
                              if (detail.globalPosition.dx >= image.dx &&
                                  detail.globalPosition.dy >= image.dy) {
                                setState(() {
                                  lastStartOffset = detail.globalPosition;
                                });
                              }
                            },
                            onPanUpdate: (detail) {
                              if (detail.globalPosition.dx >= image.dx &&
                                  detail.globalPosition.dy >= image.dy) {
                                setState(() {
                                  moveOffset = detail.globalPosition -
                                      lastStartOffset +
                                      idleOffset;
                                  moveOffset = Offset(max(0, moveOffset.dx),
                                      max(0, moveOffset.dy));
                                  index.setTopic(
                                      index.tips.goods,
                                      max(0, moveOffset.dx) - image.dx,
                                      max(0, moveOffset.dy) - image.dy);
                                });
                              }
                            },
                            onPanEnd: (detail) {
                              setState(() {
                                idleOffset = moveOffset * 1;
                              });
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(
                                        ScreenUtil().setWidth(10)),
                                    color: Color.fromRGBO(255, 255, 255, 0.75),
                                  ),
                                  height: ScreenUtil().setWidth(10),
                                  width: ScreenUtil().setWidth(10),
                                ),
                                Container(
                                  height: ScreenUtil().setWidth(3),
                                  width: ScreenUtil().setWidth(60),
                                  color: Color.fromRGBO(255, 255, 255, 0.75),
                                ),
                                ClipPath(
                                    clipper: TriangleClipper(
                                        ClipperPosition.LeftTop),
                                    child: Container(
                                      padding: EdgeInsets.symmetric(
                                          horizontal: ScreenUtil().setWidth(10),
                                          vertical: ScreenUtil().setWidth(20)),
                                      child: Row(
                                        children: <Widget>[
                                          Container(
                                              margin: EdgeInsets.only(
                                                  left: ScreenUtil()
                                                      .setWidth(50)),
                                              width: ScreenUtil().setWidth(40),
                                              height: ScreenUtil().setWidth(40),
                                              child: CachedNetworkImage(
                                               
                                                imageUrl:
                                                    index.tips.goods.picUrl,
                                                fit: BoxFit.cover,
                                                placeholder: (context, url) =>
                                                    Image.asset(
                                                        'assets/loading.jpg'),
                                              )),
                                          Container(
                                              height: ScreenUtil().setWidth(30),
                                              margin: EdgeInsets.only(
                                                  left: ScreenUtil()
                                                      .setWidth(10)),
                                              width: ScreenUtil().setWidth(150),
                                              child: Text(index.tips.goods.name,
                                                  style: TextStyle(
                                                    fontSize:
                                                        ScreenUtil().setSp(10),
                                                  ),
                                                  maxLines: 2,
                                                  overflow:
                                                      TextOverflow.ellipsis))
                                        ],
                                      ),
                                      decoration: BoxDecoration(
                                        color:
                                            Color.fromRGBO(255, 255, 255, 0.75),
                                      ),
                                    ))
                              ],
                            )),
                      ))
                  : Container()
            ]),
            Positioned(
              bottom: ScreenUtil().setHeight(50),
              child: InkWell(
                onTap: () async {
                  EasyLoading.show();
                  bool result = await index.getCollect(context);
                  EasyLoading.dismiss();
                  ScrollController scrollController = new ScrollController();
                  if (result) {
                    showDialog(
                      context: context,
                      child: Scaffold(
                        body: Container(
                          color: Color.fromRGBO(0, 0, 0, 1),
                          height: MediaQuery.of(context).size.height,
                          width: MediaQuery.of(context).size.width,
                          child: Column(
                            children: <Widget>[
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: <Widget>[
                                  InkWell(
                                      onTap: () {
                                        Navigator.of(context).pop();
                                      },
                                      child: Container(
                                          margin: EdgeInsets.all(
                                              ScreenUtil().setSp(30)),
                                          padding: EdgeInsets.symmetric(
                                              horizontal:
                                                  ScreenUtil().setWidth(40),
                                              vertical:
                                                  ScreenUtil().setWidth(10)),
                                          color: Colors.cyan[400],
                                          child: Text("取消",
                                              style: TextStyle(
                                                  color: Colors.white))))
                                ],
                              ),
                              Container(
                                child: Text("收藏的单品",
                                    style: TextStyle(color: Colors.white)),
                              ),
                              ListView(
                                shrinkWrap: true,
                                controller: scrollController,
                                children:
                                    index.collectModel.data.list.map((item) {
                                  return InkWell(
                                      onTap: () async {
                                        RenderBox renderBox = anchorKey
                                            .currentContext
                                            .findRenderObject();
                                        Offset offset = renderBox
                                            .localToGlobal(Offset.zero);
                                        await index.setTopic(
                                            item, offset.dx, offset.dy);
                                        setState(() {
                                          image = offset;
                                        });
                                        moveOffset =
                                            Offset(offset.dx, offset.dy);
                                        Navigator.of(context).pop();
                                      },
                                      child: Container(
                                        color:
                                            Color.fromRGBO(255, 255, 255, 0.3),
                                        padding: EdgeInsets.symmetric(
                                            horizontal:
                                                ScreenUtil().setWidth(20),
                                            vertical:
                                                ScreenUtil().setWidth(10)),
                                        margin: EdgeInsets.symmetric(
                                            horizontal:
                                                ScreenUtil().setWidth(10),
                                            vertical:
                                                ScreenUtil().setWidth(10)),
                                        child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Container(
                                                  width: ScreenUtil()
                                                      .setWidth(120),
                                                  height: ScreenUtil()
                                                      .setWidth(120),
                                                  child: CachedNetworkImage(
                                                    imageUrl: item.picUrl,
                                                    fit: BoxFit.cover,
                                                    placeholder: (context,
                                                            url) =>
                                                        Image.asset(
                                                            'assets/loading.jpg'),
                                                  )),
                                              Container(
                                                  width: ScreenUtil()
                                                      .setWidth(900),
                                                  padding: EdgeInsets.symmetric(
                                                      horizontal: ScreenUtil()
                                                          .setWidth(20)),
                                                  child: Text(
                                                    item.name,
                                                    style: TextStyle(
                                                        color: Colors.white),
                                                  ))
                                            ]),
                                      ));
                                }).toList(),
                              )
                            ],
                          ),
                        ),
                        backgroundColor: Colors.transparent,
                      ),
                    );
                  }
                },
                child: Container(
                    child: Row(
                  children: <Widget>[
                    Icon(
                      Icons.image,
                      color: Colors.white,
                    ),
                    Text(
                      "选择单品",
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.bold),
                    )
                  ],
                )),
              ),
            ),
          ]),
        ),
      );
    });
  }

  /*图片控件*/
  Widget _ImageView(imgPath) {
    if (imgPath == null) {
      return Center(
        child: Text("请选择图片或拍照"),
      );
    } else {
      return Image.network(
        imgPath,
        key: anchorKey,
      );
    }
  }

  /*拍照*/
  _takePhoto() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      _imgPath = image;
    });
  }

  /*相册*/
  _openGallery() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    EasyLoading.show();
    UploadModel uploadModel = await upload(context, image);
     Provide.value<AffairProvider>(context).setImage(uploadModel.data.url);
    EasyLoading.dismiss();
  }
}

class TouchMovePainter extends CustomPainter {
  var painter = Paint();
  var painterColor = Colors.red;

  @override
  void paint(Canvas canvas, Size size) {
    painter.color = painterColor;
    canvas.drawCircle(Offset(size.width / 2, size.height / 2),
        min(size.height, size.width) / 2, painter);
  }

  @override
  bool shouldRepaint(TouchMovePainter oldDelegate) {
    return oldDelegate.painterColor != painterColor;
  }
}

enum ClipperPosition {
  LeftTop,
  RightTop,
}

class TriangleClipper extends CustomClipper<Path> {
  final ClipperPosition position;
  TriangleClipper(this.position);

  @override
  Path getClip(Size size) {
    final path = Path();
    path.lineTo(size.width / 6, 0.0);

    if (position == ClipperPosition.LeftTop) {
      path.lineTo(0, size.height / 2);
      path.lineTo(size.width / 6, size.height);
      path.lineTo(size.width, size.height);
      path.lineTo(size.width, 0);
    }
    // else if (position == ClipperPosition.RightTop) {
    //  path.lineTo(size.width, 0.0);
    //  path.lineTo(0.0, size.height);
    // }
    path.close();
    return path;
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}
